package com.acme.domain.client;

import java.io.Serializable;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;

import com.acme.exceptions.ClientExistsException;

public class Bank implements Serializable {

	private static final long serialVersionUID = 1L;
	private Set<Client> clients = new HashSet<Client>();

	public Client addClient(final Client client) throws ClientExistsException {

		if (getClientByName(client.getName()) != null) {
			throw new ClientExistsException("Client with name: "
					+ client.getName() + " has already in the bank", client);

		}
		clients.add(client);
		return client;
	}

	public Client getClientByName(final String name) {
		for (Client c : clients) {
			if (c.getName().equals(name)) {
				return c;
			}
		}
		return null;
	}

	@Override
	public String toString() {

		StringBuffer clientsString = new StringBuffer("The bank has: \n");
		for (Client c : clients) {
			clientsString.append(c.toString());
		}
		return clientsString.toString();
	}

	public Set<Client> getClientsList() {
		return Collections.unmodifiableSet(clients);
	}

	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		if (clients == null) {
			result = prime * result;
		} else {
			result = prime * result + clients.hashCode();
		}
		return result;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj) {
			return true;
		}
		if (obj == null) {
			return false;
		}
		if (!(obj instanceof Bank)) {
			return false;
		}
		Bank other = (Bank) obj;
		if (clients == null) {
			if (other.clients != null) {
				return false;
			}
		} else if (!clients.equals(other.clients)) {
			return false;
		}
		return true;
	}

}
